package dbbaas;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import baas.Util;

public class CloudFileRest extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public CloudFileRest() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doDelete method of the servlet. <br>
	 * 
	 * This method is called when a HTTP delete request is received.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doDelete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * 包含save接口 保存文件至云端 为了代码可读性 这里使用commons-fileupload 上传文件
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		System.out.println("-----CloudFileRest-upload-----"
				+ df.format(new Date()));

		// 参数序列化
		// Parameter params = request.getParameter("params");
		// 定义外壳
		ResMsgItem resMsgItem = new ResMsgItem();
		resMsgItem.setCode(0);
		resMsgItem.setSum(0);
		Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sTime = format.format(new Date());
		// 紧凑的日期 如2015129909361223
		Format formatDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sDateTime = formatDate.format(new Date());
		// JSONArray jsonDataArray = new JSONArray();
		// resMsgItem.setData(jsonDataArray.toString());
		resMsgItem.setTime(sTime);

		// 获取参数
		String appkey = request.getParameter("appkey"); // 列定义
		// System.out.println("sql=" + sql);
		// 通过appkey查询apiid
		Connection conn = DBUtil.getDBConnection("cloudservice");
		Connection connCloud = null;
		String sql1 = "select appid from appconfig where appkey=\'" + appkey
				+ "\'";
		PreparedStatement pstm1;
		String sAppId = "";
		try {
			pstm1 = conn.prepareStatement(sql1);
			ResultSet rs1 = pstm1.executeQuery();
			if (rs1.next()) {
				connCloud = DBUtil.getDBConnection(rs1.getString("appid"));
				sAppId = rs1.getString("appid");
				;
			} else {
				resMsgItem.setCode(1);
				resMsgItem.setStatus(1);
				resMsgItem.setMessage("error");
				Util.writeJsonToResponse(response, resMsgItem);
			}
			// PreparedStatement pstm2 = conn.prepareStatement(sql);
			// ResultSet rs2 = pstm2.executeQuery();
			// 通过appid查询指向的数据库
			// 判断数据库是否存在
			// 通过指向的数据库得到Conn 数据库连接

			// 通过数据库连接执行SQL
			if (connCloud != null && !connCloud.isClosed()) {
				String contentPath = getServletContext().getRealPath("/");
				File contentPathFile = new File(contentPath);
				if (!contentPathFile.exists() && !contentPathFile.isDirectory()) {  
					contentPathFile.mkdirs();  
	            }
				String imgFileFolder = contentPath + sAppId + "\\files";
				File uploadPath = new File(imgFileFolder);
				if (!uploadPath.exists() && !uploadPath.isDirectory()) {  
					uploadPath.mkdirs();  
	            }  
				PrintWriter writer = response.getWriter();
				String contentType = request.getContentType();
				if (ServletFileUpload.isMultipartContent(request)) {// 检查输入请求是否为multipart表单数据
					try {
						FileItemFactory factory = new DiskFileItemFactory();
						ServletFileUpload upload = new ServletFileUpload(
								factory);
						String fileName = "";
						List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
						if (items != null && items.size() > 0) {
							FileItem item = items.get(0);// 仅处理第一个
							boolean flag = false;
							// 添加精确到毫秒的时间到文件名前面
							fileName = sDateTime + "_" + item.getName();// 获得文件名，包括路径
							if (fileName != null) {
								File fullFile = new File(fileName);
								File savedFile = new File(uploadPath,
										fullFile.getName());
								try {
									item.write(savedFile);
									flag = true;
								} catch (Exception e) {
									// TODO Auto-generated catch block
								}
							}
							String fileUrl = "/" + sAppId + "/files/"
									+ fileName;
							String saveFileLog = "saveFile filename:flag="
									+ flag
									+ "|uuid=@uuid|fileUrl=@fileUrl|filepath=@filepath";
							saveFileLog = saveFileLog.replace("@fileUrl",
									fileUrl);
							saveFileLog = saveFileLog.replace("@filepath",
									imgFileFolder + fileName);
							saveFileLog = saveFileLog.replace("@uuid",
									item.getFieldName());
							System.out.println(saveFileLog);
							if (flag) {
								String sInsertPhoto = "Insert into picture(pic_code,pic_road) values(?,?)";
								PreparedStatement newStat = connCloud
										.prepareStatement(sInsertPhoto);
								newStat.setString(1, item.getFieldName());
								newStat.setString(2, fileUrl);
								try {
									newStat.execute();
								} catch (SQLException e) {
									resMsgItem.setCode(1);
									resMsgItem.setMessage(e.getMessage());
									resMsgItem.setMsg("执行脚本错误！");
									Util.writeJsonToResponse(response,
											resMsgItem);
								} finally {
									newStat.close();
								}
								// writer.write(Utils.toData(null,0,"success"));
								resMsgItem.setCode(0);
								resMsgItem.setMessage("success");
								resMsgItem.setMsg("保存文件成功！");
								Util.writeJsonToResponse(response, resMsgItem);
							} else {
								resMsgItem.setCode(1);
								resMsgItem.setMessage("error");
								resMsgItem.setMsg("保存文件失败！");
								Util.writeJsonToResponse(response, resMsgItem);
								// writer.write(Utils.toData(null,1,"error"));
							}
						}
					} catch (FileUploadException e) {
						System.out.println("saveFile field:" + e.getMessage());
						resMsgItem.setCode(1002);
						resMsgItem.setMessage("parse Request file Field");
						resMsgItem.setMsg("parse Request file Field");
						Util.writeJsonToResponse(response, resMsgItem);
						// writer.write(Utils.toData(null, 1002,
						// "parse Request file Field" + e.getMessage()));
					}
				} else {
					resMsgItem.setCode(1002);
					resMsgItem.setMessage("bad parameter");
					resMsgItem.setMsg("参数不符合规范返回值");
					Util.writeJsonToResponse(response, resMsgItem);
					// writer.write(Utils.toData(null, 1002, "bad parameter")
					// + contentType);// 参数不符合规范返回值
				}
				// writer.close();
			}
			// 释放连接
			connCloud.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		// String contentPath = getServletContext().getRealPath("/");
		// String imgFileFolder = contentPath + "files";
		// File uploadPath = new File(imgFileFolder);
		// PrintWriter writer = response.getWriter();
		// String contentType = request.getContentType();
		// if (ServletFileUpload.isMultipartContent(request)) {//
		// 检查输入请求是否为multipart表单数据
		// try {
		// FileItemFactory factory = new DiskFileItemFactory();
		// ServletFileUpload upload = new ServletFileUpload(factory);
		// List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
		// if (items != null && items.size() > 0) {
		// FileItem item = items.get(0);// 仅处理第一个
		// // SaeStorage storage = new SaeStorage();
		// // 注意这里使用的是getFieldName 而不是文件的真实名称考虑到文件名中可能包含路径
		// // boolean flag = storage.write(DOMAIN, item.getFieldName(),
		// // item.get());
		// boolean flag = false;
		// String fileName = item.getName();// 获得文件名，包括路径
		// // fileName = dtFileName;
		// if (fileName != null) {
		//
		// File fullFile = new File(fileName);
		// File savedFile = new File(uploadPath,
		// fullFile.getName());
		// try {
		// item.write(savedFile);
		// flag = true;
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// }
		// }
		// // logger.debug("saveFile filename:" + item.getFieldName()
		// // + "|flag:" + flag);
		// if (flag) {
		// writer.write(Utils.toData(null,0,"success"));
		// } else {
		// writer.write(Utils.toData(null,1,"error"));
		// }
		// }
		// } catch (FileUploadException e) {
		// // logger.debug("saveFile field:" + e.getMessage());
		// writer.write(Utils.toData(null, 1002,
		// "parse Request file Field" + e.getMessage()));
		// }
		// } else {
		// writer.write(Utils.toData(null, 1002, "bad parameter")
		// + contentType);// 参数不符合规范返回值
		// }
		// writer.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
